package com.henu.ocr.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.henu.ocr.entity.Company;
import com.henu.ocr.mapper.CompanyMapper;
import com.henu.ocr.service.CompanyService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Future;

/**
 * @author 25612
 */
@Service
@EnableAsync
@SuppressWarnings("all")
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {
    @Override
    public List<Company> findAllCompany() {
        return this.list();
    }

    @Override
    public Company findCompanyById(Integer id) {
        return this.getById(id);
    }

    @Override
    public List<Company> findSubCompanyById(Integer id) {
        //查找father_company为id的子公司
        return this.list((new QueryWrapper<Company>()).eq("father_company", id));
    }

    @Async
    @Override
    public Future<Boolean> completeCompanyDetailsAsync(Company company, String fathercorp_mdmCode) {
        try {
            if ("0".equals(fathercorp_mdmCode)) {
                company.setIndexs("0/" + company.getCompanyId());
                company.setFatherCompanyId(0);
            } else {
                Company fatherCompany = findCompanyByMdmCode(fathercorp_mdmCode);
                company.setIndexs((fatherCompany.getIndexs()) + "/" + company.getCompanyId());
                company.setFatherCompanyId(fatherCompany.getCompanyId());
            }
            //局，公司，分公司 的判定还没写
            return AsyncResult.forValue(updateCompanyWithIndexs(company));
        } catch (Exception e) {
            log.error("completeCompanyDetailsAsync failed," + e.getMessage());
            return AsyncResult.forValue(false);
        }
    }

    @Cacheable(value = "company", key = "'company'+#mdmCode")
    @Override
    public Company findCompanyByMdmCode(String mdmCode) {
        return this.getOne((new QueryWrapper<Company>()).eq("mdm_code", mdmCode));
    }

    @CacheEvict(value = "company", key = "'company'+#company.mdmCode")
    @Override
    public boolean updateCompanyWithIndexs(Company company) {
        return this.updateById(company);
    }
}
